package com.sg.common.db;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.sg.common.log.MyLog;
import com.sg.common.utils.DesUtils;

/**
 * Druid数据库连接池配置类
 * @author qianxiaowei
 *
 */
public class DruidPool  {
    private DruidDataSource dds = null;
    DruidPool(String propertyFile) {
        Properties properties = loadPropertyFile("properties/jdbc/"+propertyFile+".properties");
        try {
        	String password=properties.getProperty("password");
        	properties.put("password", DesUtils.decrypt(password,"sgyyxxhk"));
            dds = (DruidDataSource) DruidDataSourceFactory
                    .createDataSource(properties);
        } catch (Exception e) {
            MyLog.err(e.getMessage());
        }
    }
    public DruidPooledConnection getConnection() throws SQLException {
        return dds.getConnection();
    }
    private Properties loadPropertyFile(String fullFile) {
        String webRootPath = null;
        if (null == fullFile || fullFile.equals(""))
            throw new IllegalArgumentException(
                    "Properties file path can not be null : " + fullFile);
        webRootPath = DruidPool.class.getClassLoader().getResource("")
                .getPath().replaceAll("%20", " ");
//        webRootPath = new File(webRootPath).getParent();
        InputStream inputStream = null;
        Properties p = null;
        try {
            inputStream = new FileInputStream(new File(webRootPath
                    + File.separator + fullFile));
            p = new Properties();
            p.load(inputStream);
        } catch (FileNotFoundException e) {
            throw new IllegalArgumentException("Properties file not found: "
                    + webRootPath
                    + File.separator + fullFile);
        } catch (IOException e) {
            throw new IllegalArgumentException(
                    "Properties file can not be loading: " + webRootPath
                    + File.separator + fullFile);
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return p;
    }
}
